// db.js - 数据库访问层

const { MongoClient } = require('mongodb');

class Database {
  constructor(url = 'mongodb://127.0.0.1:27017/blog') {
    // this.url = url;
    this.client = new MongoClient(url);
  }

  async connect () {
    await this.client.connect();  //返回的是一个promeses
    console.log('数据库已连接');
    this.db = this.client.db();
  }
  async disconnect () {
    await this.client.close();
  }
//新增一条数据
  async insertOne (collectionName, document) {
    const collection = this.db.collection(collectionName);
    const result = await collection.insertOne(document);
    return result;
  }

  async findOne (collectionName, query) {
    const collection = this.db.collection(collectionName);
    const result = await collection.findOne(query);
    return result;
  }
  async find (collectionName, query = {}) {
    const collection = this.db.collection(collectionName);
    const result = await collection.find(query).toArray();
    return result;
  }
  async updateOne (collectionName, query1 = {}, query2 = {}) {
    const collection = this.db.collection(collectionName);
    const result = await collection.updateOne(query1, { $set: query2 });
    return result;
  }
  async deleteMany (collectionName, query = {}) {
    const collection = this.db.collection(collectionName);
    const result = await collection.deleteMany(query);
    return result;
  }
  // 其他数据库操作方法...const deleteResult = await collection.deleteMany({ a: 3 });
}

module.exports = Database;
